package com.artup.service.impl;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.artup.common.Constants;
import com.artup.common.ResponseResult;
import com.artup.dao.DeskCalendarDao;
import com.artup.pojo.DeskCalendar;
import com.artup.service.DeskCalendarService;
import com.artup.util.CommonUtils;
import com.artup.util.file.FileUploadUtil;
import com.artup.util.file.PropertiesUtils;
import com.artup.util.os.OperationSystemInfo;
import com.artup.util.shell.ChmodShell;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service( value = "deskCalendarService" )
public class DeskCalendarServiceImpl implements DeskCalendarService {
	@Autowired
	private DeskCalendarDao deskCalendarDao; 

	@Override
	public ResponseResult queryDeskCalendarList(DeskCalendar deskCalendar) {
		log.info("deskCalendar = {}", JSONObject.toJSONString(deskCalendar));
		
		ResponseResult responseResult = new ResponseResult();
		
		/*if(null == beginYearMonth || null == endYearMonth) {
			log.warn("【起始年月】或【结束年月】不可为空！");
			
			responseResult.setStatus(Constants.ACTION_STATUS_NOT_MORE_THAN_ZERO);
			responseResult.setMessage("【起始年月】或【结束年月】不可为空！");
			
			return responseResult;
		} else if(2000 >= beginYearMonth || 2000 >= endYearMonth) {
			log.warn("【起始年月】或【结束年月】不可早于 2000 年！");
			
			responseResult.setStatus(Constants.ACTION_STATUS_NOT_MORE_THAN_ZERO);
			responseResult.setMessage("【起始年月】或【结束年月】不可早于 2000 年！");
			
			return responseResult;
		} else if(6 != String.valueOf(beginYearMonth).length() || 6 != String.valueOf(endYearMonth).length()) {
			log.warn("【起始年月】或【结束年月】不是有效的日期！");
			
			responseResult.setStatus(Constants.ACTION_STATUS_NOT_MORE_THAN_ZERO);
			responseResult.setMessage("【【起始年月】或【结束年月】不是有效的日期！");
			
			return responseResult;
		} else if(beginYearMonth > endYearMonth) {
			log.warn("【起始年月】不可晚于【结束年月】！");
			
			responseResult.setStatus(Constants.ACTION_STATUS_NOT_MORE_THAN_ZERO);
			responseResult.setMessage("【起始年月】不可晚于【结束年月】！");
			
			return responseResult;
		}*/
		
		long totalCount = 0;
		try {
			totalCount = this.deskCalendarDao.selectDeskCalendarTotalCount(deskCalendar);
		} catch (SQLException e) {
			log.error("查询【台历】总记录数 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("查询【台历】总记录数 - 失败！");
			
			return responseResult;
		}
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("totalCount", totalCount);
		
		if(0 == totalCount) {
			responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
			responseResult.setMessage("查询【台历】列表 - 成功。");
			responseResult.setData(resultMap);
			
			return responseResult;
		}
		
		if(null == deskCalendar.getPageIndex() || 0 >= deskCalendar.getPageIndex()) {
			deskCalendar.setPageIndex(1);
		}
		if(null == deskCalendar.getPageSize() || 0 >= deskCalendar.getPageSize()) {
			deskCalendar.setPageSize(Integer.valueOf(PropertiesUtils.getValue("pagination.pageSize")));
		}
		
		long offset = (deskCalendar.getPageIndex() - 1) * deskCalendar.getPageSize();	// 起始订单行号
		deskCalendar.setOffset(offset);
		
		List<DeskCalendar> deskCalendarList = null;
		try {
			deskCalendarList = this.deskCalendarDao.selectDeskCalendarList(deskCalendar);
		} catch (SQLException e) {
			log.error("查询【台历】列表 - 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("查询【台历】列表 - 失败！");
			
			return responseResult;
		}
		
		resultMap.put("deskCalendarList", deskCalendarList);
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("查询【台历】列表 - 成功。");
		responseResult.setData(resultMap);
		
		return responseResult;
	}

	@Override
	public ResponseResult saveDeskCalendar(Integer name, String skuCode, MultipartHttpServletRequest multipartRequest) {
		log.info("name = {}, skuCode = {}", name, skuCode);
		
		ResponseResult responseResult = new ResponseResult();
		
		if(null == name) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_EMPTY);
			responseResult.setMessage("【名称】不可为空！");
			
			return responseResult;
		} else if(2000 >= name) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_NOT_POSITIVE_INTEGER);
			responseResult.setMessage("【名称】为正整数！");
			
			return responseResult;
		} else if(StringUtils.isBlank(skuCode)) {
			responseResult.setStatus(Constants.ACTION_STATUS_PARAMETER_NOT_POSITIVE_INTEGER);
			responseResult.setMessage("【SKU 编号】不可为空！");
			
			return responseResult;
		}
		
		if(null == multipartRequest || !multipartRequest.getFileNames().hasNext()){
			return null;
		}
		
		DeskCalendar deskCalendar = new DeskCalendar();
		deskCalendar.setName(name);
		deskCalendar.setSkuCode(skuCode);
		
		for (Iterator<?> fileIterator = multipartRequest.getFileNames(); fileIterator.hasNext();) {  
			String key = (String) fileIterator.next();  
			MultipartFile multipartFile = multipartRequest.getFile(key);  
			
			if(null == multipartFile || 0 == multipartFile.getSize()){
				continue;
			}
			
			String originalFileName = multipartFile.getOriginalFilename();
			String contentType = multipartFile.getContentType();
			String fileName = multipartFile.getName();
			long fileSize = multipartFile.getSize();
			
			log.info("originalFileName = "
					+ originalFileName + ", contentType = " + contentType
					+ ", fileName = " + fileName + ", fileSize = " + fileSize);

			if(500 > fileSize) {
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("图片大小不可小于 500 KB!");
				
				return responseResult;
			} else if(31457280 < fileSize) {
				responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
				responseResult.setMessage("图片大小不可大于 30 MB!");
				
				return responseResult;
			}
			
			String expandedName = originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length());
			
			deskCalendar.setOriginalImageName(originalFileName);
			if(StringUtils.isNotBlank(expandedName)) {
				deskCalendar.setExpandedName(expandedName.substring(1, expandedName.length()));
			}
			deskCalendar.setImageSize(fileSize);
			
			String systemFileName = CommonUtils.UUIDGenerator() + expandedName;
			
			String uploadPrefix = PropertiesUtils.getValue("works.image.deskCalendar");

			deskCalendar.setImagePath(uploadPrefix + systemFileName);
			
			try {
				FileUploadUtil.saveFileFromInputStream(multipartFile.getInputStream(),
						uploadPrefix, systemFileName);
			} catch (Exception e) {
				log.error("保存文件到磁盘 - 失败！", e);
			}  
			
			if(OperationSystemInfo.isLinux()) {
				ChmodShell.updateFolderAuth(deskCalendar.getImagePath());
			}
		}  

		try {
			this.deskCalendarDao.insertDeskCalendar(deskCalendar);
		} catch (SQLException e) {
			log.error("保存【台历】- 失败！", e);
			
			responseResult.setStatus(Constants.ACTION_STATUS_FAILURE);
			responseResult.setMessage("保存【台历】 - 失败！");
		}
		
		responseResult.setStatus(Constants.ACTION_STATUS_SUCCESS);
		responseResult.setMessage("保存【台历】 - 成功。");
		
		return responseResult;
	}
}
